﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Xinkui.WebModel.Cache.View;
using Xinkui.DataAccess.AutoGenerator;
using Xinkui.Common;
using Xinkui.Entity.AutoGenerator;

namespace Xinkui.WebModel.Cache
{
    public static class CategoryCache
    {

        public static List<CategoryView> ListCategoryByCompany(int companyId)
        {
            return CacheProxy.Get<List<CategoryView>>(SystemConst.CacheConst.GetShowRoomCategoryKey(companyId), () =>
            {
                return ListCategoryByCompanyFromDb(companyId);
            });
        }

        public static List<CategoryView> ListAllCategory()
        {
            return CacheProxy.Get<List<CategoryView>>(SystemConst.CacheConst.GetCategoryKey(), () =>
            {
                return ListAllCategoryFromDb();
            });

        }

        public static List<CategoryView> ListAllCategoryFromDb()
        {
            var allCategoryList = Singleton<CommonCategoryDataAccess>.Instance.ListAllCategory();
            var level1Categorys = allCategoryList.Where(u => u.Depth == 1);
            List<CategoryView> returnDatas = new List<CategoryView>(level1Categorys.Count());
            Func<int, List<CommonCategory_Entity>> getDataFunc = a => { return allCategoryList.Where(u => u.ParentID == a).ToList(); };
            foreach (var level1Item in level1Categorys)
            {
                returnDatas.Add(CategoryView.GetInstance(null, level1Item, getDataFunc));
            }

            return returnDatas;
        }

        public static List<CategoryView> ListCategoryByCompanyFromDb(int companyId)
        {
            var allCategoryList = Singleton<CommonCategoryDataAccess>.Instance.ListShowRoonCategory(companyId);
            var level1Categorys = allCategoryList.Where(u => u.Depth == 1);
            allCategoryList.RemoveAll(u => u.Depth != 1 && !u.IsFloor && u.ProductCount == 0);

            List<CategoryView> returnDatas = new List<CategoryView>(level1Categorys.Count());
            Func<int, List<CommonCategory_Entity>> getDataFunc = a => { return allCategoryList.Where(u => u.ParentID == a).ToList(); };
            foreach (var level1Item in level1Categorys)
            {
                returnDatas.Add(CategoryView.GetInstance(null, level1Item, getDataFunc));
            }

            return returnDatas;
        }
    }
}
